dojo.require("dojox.grid._data.editors");

// Utility function
function obj2Str(o) {
	var _out = ""; for(var _m in o) {if(!dojo.isFunction(o[_m])) _out += ("{ "+_m+"="+o[_m]+" } ");}; return _out;
}

var PageAdmin = (function() {
/* Declare private static variables here */

//
//
//
function constructor() {

}

constructor.ACTION_UPDATE = "_update_";
constructor.ACTION_CREATE = "_create_";

// tree view page node id 
constructor.NODE_ID = "pag";

// page map [name,value]
constructor.pages =[];

//
//
//
constructor.onLoad =  function() {

	// Fill pages node
	adminTreeModel.fetch( {query:{id:this.NODE_ID }, onComplete: function(items, request) {
		console.debug( "item "+items[0].name );		
		constructor._loadPages( {item:items[0], store:adminTreeModel} );
				
	}}  );	
	
	// item selected on the tree 
	var _item = null;
	
	// CREATE TREE POPUP MENU
	var menu = new dijit.Menu({targetNodeIds:["adminTree"], id:"progMenu"});
   	var operation = new dijit.Menu({label:"operation", id:"progPopupMenuItem"}); 
    operation.addChild(new dijit.MenuItem({label:"Submenu item", 
    		onClick:function(){ 
    			constructor.openDialog( _item.name );
    		}}));
    operation.addChild(new dijit.MenuItem({label:"Submenu item", 
    		onClick:function(){ 
    			alert('Update Page ' + _item.name );
    		}}));

	operation.connect( operation, "_onBlur", function(e){dijit.popup.close(operation);});
	 
	menu.connect( menu, "_openMyself", function(e){
		// get a hold of, and log out, the tree node that was the source of this open event
		var tn = dijit.getEnclosingWidget(e.target);
		
		_item = tn.item;
		
		if( typeof _item.parentId != "undefined" && constructor.NODE_ID==_item.parentId ) {	
			
			//var _x = e.target.offsetLeft+e.target.offsetWidth+e.target.scrollLeft;
			//var _y = e.target.offsetTop+e.target.offsetHeight+e.target.scrollHeight;
	
			var _y = e.pageY+e.target.scrollLeft;
			var _x = e.pageX+e.target.scrollLeft;;
			
	    	dijit.popup.open( {popup:operation, x:_x, y:_y} );
	    	operation.focus();
	    	
		}
		else {
			dijit.popup.close(operation);
		}					

	});
	
}


//
//
//
constructor.openDialog = function() {
	var dialog = dijit.byId('pageDialog');

	var input_action	= dijit.byId("action");		
	var input_template	= dijit.byId("template");
	var	table			= dojo.byId("pageVarsDiv");
	
	table.innerHTML = "";
	
	if( arguments.length == 1 ) {
		input_action.setValue(this.ACTION_UPDATE);
		input_template.setDisabled(true);

		var p = this.pages[arguments[0]];
		
		var input_name = dijit.byId("name");
		input_name.setValue(p.name);
		
		
		constructor.displayPageVars(p);
	}
	else {
		input_action.setValue(this.ACTION_CREATE);
		input_template.setDisabled(false);
	}
	
	dialog.show();
}

//
//
//
constructor.closeDialog = function() {
	var dialog = dijit.byId('pageDialog');

	dialog.hide();
}

//
// 
//@ctx object {item: tree parent item, store: data store}
//
constructor.open = function(ctx) {
	var name = ctx.store.getValue( ctx.item, 'name');
	console.debug( "openPage "+name );			
	
	var win = window.open( "/osgip/service/"+ name,  
							name, 
							"status=0,menubar=0,resizable=1,scrollbars=1,addressbar=0");
}

//
// set global variable 'pages' and fill main tree view
//
//@context object {item: tree parent item, store: data store}
constructor._loadPages = function( context ) {
	console.debug( "_loadPages" );		
	try {

	  var pp = jsonrpc.portal.getPages();
	  			
	  var pInfo =  {parent:context.item, attribute:"children"};
	  
	  for( var i=0; i<pp.length; ++i ) {
	
		var p = pp[i];

		this.pages[p.name] = p;

		console.debug(p.name);

 		context.store.newItem( {id:p.name, name:p.name, parentId:constructor.NODE_ID, action:function(ctx){ constructor.open(ctx)}},pInfo);
		    
	  }
	  
	  
	}
	catch(e)
	{
	  console.error(e);
	}
}
	
//
// imply global vars:
//		 templateStore: ItemFileReadStore
//		 templates: object array
//		 variableGrid: dojox.grid.Grid
// 
constructor.createPageVars = function ( items, request ) {
		
		if( items.length!=1 ) {
			console.error( "more that one template found! " + request );
			return;
		}

		console.debug( templateStore.getAttributes(items[0])  );
		
		var index = templateStore.getValue( items[0], 'index' );		
		var va = templates[index].variableArray; //templateStore.getValue( items[0], 'vars' );		

		// create table for page2		
		var	table = dojo.byId("pageVarsDiv");

		var tableHTML = "<table>";
		for( i=0 ; i<va.length; ++i ) {

			tableHTML += "<tr><td><input type=\"text\" id=\"tvar_"+i+"\"  /></td>" +
						 "<td><select id=\"panel_"+i+"\" ></select></td></tr>";
		}
		tableHTML += "</table>";
		
		table.innerHTML = tableHTML;
				
		for( i=0 ; i<va.length; ++i ) {

			var text = dijit.byId( "tvar_"+i );
			var val  = dijit.byId( "panel_"+i );

			if( text ) text.destroy();
			if( val ) val.destroy();
			 
			text = new dijit.form.TextBox({
					name:"tvar."+i,
					trim:true
					}, dojo.byId("tvar_"+i));
			text.setValue(va[i].name);
			
			val = new dijit.form.ComboBox({
					name:"panel."+i,
					autoComplete:false,
					store:panelsStore,
					style:"width:350px"
					}, dojo.byId("panel_"+i));
			
			if( va[i].defaultValue!=null) {
				val.setValue( "\""+va[i].defaultValue+"\"" );
			}				
		}				
}

//
// @param p page object
constructor.displayPageVars = function ( p ) {
		
		//console.debug( "page " + dojo.toJson(p) );
		
		var va = p.variableArray;
		 
		// create table for page2		
		var	table = dojo.byId("pageVarsDiv");

		var tableHTML = "<table>";
		for( i=0 ; i<va.length; ++i ) {

			tableHTML += "<tr><td><input type=\"text\" id=\"tvar_"+i+"\"  /></td>" +
						 "<td><select id=\"panel_"+i+"\" ></select></td></tr>";
		}
		tableHTML += "</table>";
		
		table.innerHTML = tableHTML;
				
		for( i=0 ; i<va.length; ++i ) {

			var text = dijit.byId( "tvar_"+i );
			var val  = dijit.byId( "panel_"+i );

			if( text ) text.destroy();
			if( val ) val.destroy();
			 
			text = new dijit.form.TextBox({
					name:"tvar."+i,
					trim:true
					}, dojo.byId("tvar_"+i));
			text.setValue(va[i].name);
			
			val = new dijit.form.ComboBox({
					name:"panel."+i,
					autoComplete:false,
					store:panelsStore,
					style:"width:350px"
					}, dojo.byId("panel_"+i));
			
			val.setValue( va[i].value );
		}				
}

//
//
//@param form source form 
constructor.submitPageDialog =  function( form ) {

	console.debug( "form "+dojo.toJson(form) );

	var tv = new Array();
	var vv = new Array();

	var i = 0; for( var m in form.tvar )	tv[i++] = form.tvar[m];
		i = 0; for( var m in form.panel )	vv[i++] = form.panel[m];
	
	try	{
		if( this.ACTION_CREATE==form.action ) {
			constructor._createPage( form.name, form.template, tv, vv );
		}
		else {
			constructor._updatePage( form.name, tv, vv );
		}
	} catch(e) {
		console.error(e);
	}	
}

//
//
//@param name page name
//@param tv var names 
//@param vv var values 
constructor._updatePage =  function( name, vn, vv ) {
	jsonrpc.portal.storePage( name, vn, vv );
}

//
//
//@param name page name
//@param tname tamplate name
//@param tv var names 
//@param vv var values 
constructor._createPage =  function( name, tname, tv, vv ) {

	var p = jsonrpc.portal.createPage( name, tname, tv, vv );

	console.debug( "created page "+p );
	
	this.pages[name] = p;
	
	// Fill pages node
	adminTreeModel.fetch( {query:{id: constructor.NODE_ID}, onComplete: function(items, request) {	
			var pInfo =  {parent:items[0], attribute:"children"};
				
			adminTreeModel.newItem( {id:page.name, name:page.name, action:function(ctx){ PageAdmin.open(ctx)}},pInfo);					
		}} );	
		
		
}

	
return constructor;
})();

